package xyz.luhui1hao.springboottest.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xyz.luhui1hao.springboottest.domain.User;
import xyz.luhui1hao.springboottest.service.UserService;
import xyz.luhui1hao.springboottest.utils.JacksonUtils;

import java.util.List;

//@RestController注解能够使项目支持Rest
@RestController
//表示该controller类下所有的方法都公用的一级上下文根
@RequestMapping(value = "/springboot")
public class UserController {

    @Autowired
    private UserService userService;

    //这里使用@RequestMapping注解表示该方法对应的二级上下文路径
    @RequestMapping(value = "/getUserByGet", method = RequestMethod.GET)
    String getUserByGet(@RequestParam(value = "userName") String userName){
        return "Hello " + userName;
    }

    //通过RequestMethod.POST表示请求需要时POST方式
    @RequestMapping(value = "/getUserByPost", method = RequestMethod.POST)
    String getUserByPost(@RequestParam(value = "userName") String userName){
        return "Hello " + userName;
    }

    //在入参设置@RequestBody注解表示接收整个报文体，这里主要用在接收整个POST请求中的json报文体，
    //目前主流的请求报文也都是JSON格式了，使用该注解就能够获取整个JSON报文体作为入参，使用JSON解析工具解析后获取具体参数
    @RequestMapping(value = "/getUserByJson",method = RequestMethod.POST)
    int getUserByJson(@RequestBody String data){
        int count = 0;
        try {
            User user = JacksonUtils.json2pojo(data, User.class);
            count = userService.insertUser(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }

    @RequestMapping(value = "/insertUser", method = RequestMethod.POST)
    int insertUser(@RequestBody String data){
        int count = 0;
        try {
            User user = JacksonUtils.json2pojo(data, User.class);
            count = userService.insertUser(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }

    @RequestMapping(value = "/findUserByName", method = RequestMethod.POST)
    @ResponseBody
    String findUserByName(@RequestParam(value = "userName") String userName){
        List<User> list = userService.findUserByName(userName);
        String result = "";
        try {
             result = JacksonUtils.obj2json(list);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
}
